<?php
namespace app\common\logic;

use think\Model;
use think\Session;
use app\common\model\User as UserModel;
use app\common\logic\User as UserLogic;
use app\common\model\AuthGroup;
use app\common\model\AuthAccess;

class Passport extends Model
{
    /**
     * 用户登陆
     *
     * @params $username string 用户名
     * @params $password string 密码
     * @return boolean
     */
    public function login($username, $password)
    {
        $user = UserModel::getDetail($username);
        if (empty($user)) {
            return 1107;
        }

        if ($user['status'] == 1) {
            return 1108;
        }

        // echo $user['password'];die;
        if (!password_verify($password, $user['password'])) {
            return 1109;
        }

        $user['group_name'] = AuthGroup::getName($user['group_id']);
        self::auth($user);

        // 记录登陆日志行为事件
        $params = ['uid'        => $user['uid'],
                   'login_time' => date('Y-m-d H:i:s',time()),
                   'login_ip'   => get_client_ip()
                  ];
        \think\Hook::listen('login',$params);

        return 200;
    }

    /**
     * 创建用户登陆授权
     *
     * @params $user array 用户信息
     * @return array
     */
    private function auth($user)
    {
        $auth = array(
            'uid'        => $user['uid'],
            'group_id'   => $user['group_id'],
            'group_name' => $user['group_name'],
            'username'   => $user['username'],
            'nickname'   => $user['nickname'],
            'state'      => $user['state'],
            'login_time' => time(),
        );

        session('user_auth', $auth);
        session('user_access', AuthAccess::getAccess($user['group_id']));
        session('user_auth_sign', $this->sign($auth));
    }
    
    /**
     * 数据签名认证
     *
     * @param array $user 被认证的数据
     * @return string 签名
     */
    public function sign($auth)
    {
        // 数据类型检测
        if (!is_array($auth)) {
            $auth = (array)$auth;
        }

        ksort($auth); //排序

        // url编码并生成query字符串
        $code = http_build_query($auth);

        // 生成签名
        $sign = sha1($code);
        return $sign;
    }

    /**
     * 清空session
     *
     * @return
     */
    public function clear()
    {
        // 清除session（当前作用域）
        Session::clear();
        // 清除think作用域
        Session::clear('think');
    }
}